package com.xbongbong.saas.model.impl;

import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.DefaultAttrPoJo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.template.pojo.EnablePojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StockConstant;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.ListBusinessTypeEnum;
import com.xbongbong.saas.enums.ListGroupEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.FormTemplateModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2022/01/18 15:35
 */
@Service("formTemplateModel")
public class FormTemplateModelImpl implements FormTemplateModel {

    private static final Logger LOG = LoggerFactory.getLogger(FormTemplateModelImpl.class);

    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private CompanyConfigModel companyConfigModel;


    @Override
    public List<PaasFormEntityExt> getEnableFormList(String corpid, UserVO loginUser, Integer businessType, Long appId, Integer distributorMark) throws XbbException {
        List<PaasFormEntityExt> paasFormEntityExtList = new ArrayList<>();
        try {
            if (Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
                List<WorkOrderFormEntity> workOrderFormEntities = workOrderFormModel.getTemplateWithPermission(corpid, loginUser, appId, null);
                BeanUtil.copyPropertiesList(workOrderFormEntities, paasFormEntityExtList, PaasFormEntityExt.class);
            } else if (Objects.equals(businessType,XbbRefTypeEnum.PRODUCT_WAREHOUSE.getCode())){
                paasFormEntityExtList = paasFormModel.getEnableFormList(corpid, XbbRefTypeEnum.WAREHOUSE.getCode());
            } else if (Objects.equals(businessType,XbbRefTypeEnum.WORK_REPORT.getCode())){
                paasFormEntityExtList = paasFormModel.getWorkReportTemplateWithPermission(corpid, loginUser, appId, null);
            } else {
                // 查询需要兼容经销商
                Map<String,Object> map = new HashMap<>();
                map.put("corpid", corpid);
                map.put("businessType", businessType);
                map.put("del", 0);
                map.put("enable",1);
                map.put("distributorMark", distributorMark);
                map.put("hidden", 0);
                paasFormEntityExtList = paasFormModel.list(map);
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormModelImpl.getEnableFormList  出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return paasFormEntityExtList;
    }


    @Override
    public List<PaasFormEntityExt> getSaasFormList(String corpid, PaasFormEntityExt form,  Integer subBusinessType, UserVO loginUser) throws XbbException {
        // templateService.getSaasTemplateList
        List<PaasFormEntityExt> paasFormEntityList = new ArrayList<>();
        Integer saasMark = form.getSaasMark();
        Integer distributorMark = form.getDistributorMark();
        Integer businessType = 0;
        if (Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark)) {
            if (Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_PURCHASE.getCode()) || Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_PRODUCE.getCode())){
                //待出入库拼接列表
                PaasFormEntityExt contractForm = paasFormModel.getByBusinessType(XbbRefTypeEnum.CONTRACT.getCode(), corpid);
                contractForm.setName(I18nMessageUtil.getMessage(I18nStringConstant.OUT_OF_STOCK_CONTRACT) + (Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_PURCHASE.getCode()) ? I18nMessageUtil.getMessage(I18nStringConstant.PURCHASE) : I18nMessageUtil.getMessage(I18nStringConstant.PRODUCE)));
                PaasFormEntityExt productForm = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
                productForm.setName(I18nMessageUtil.getMessage(I18nStringConstant.OUT_OF_STOCK_PRODUCT)  + (Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_PURCHASE.getCode()) ? I18nMessageUtil.getMessage(I18nStringConstant.PURCHASE) : I18nMessageUtil.getMessage(I18nStringConstant.PRODUCE)));
                paasFormEntityList.add(contractForm);
                paasFormEntityList.add(productForm);
            } else if (Objects.equals(subBusinessType,XbbRefTypeEnum.SMART_REPLENISHMENT.getCode())){
                PaasFormEntityExt productForm = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
                productForm.setName(I18nMessageUtil.getMessage(I18nStringConstant.OUT_OF_STOCK_PRODUCT)  + (Objects.equals(subBusinessType,XbbRefTypeEnum.WAIT_PURCHASE.getCode()) ? I18nMessageUtil.getMessage(I18nStringConstant.PURCHASE) : I18nMessageUtil.getMessage(I18nStringConstant.PRODUCE)));
                paasFormEntityList.add(productForm);
            }else if (Objects.equals(subBusinessType,XbbRefTypeEnum.CUSTOMER_STATEMENT.getCode())){
                // 默认获取客户模板和经销商模板
                Map<String, Object> param = new HashMap<>(16);
                param.put("businessType", XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                param.put("enable", 1);
                param.put("del", DelEnum.NORMAL.getDel());
                param.put("corpid", corpid);
                param.put("hidden", 0);
                List<PaasFormEntityExt> paasFormEntityExts= paasFormModel.getByBusinessTypes(param);
                paasFormEntityList.addAll(paasFormEntityExts);
            } else if (Objects.equals(subBusinessType,XbbRefTypeEnum.CUSTOMER_STATEMENT_STATISTIC.getCode())){
                businessType = subBusinessType;
                Map<String, Object> param = new HashMap<>(16);
                param.put("businessType", businessType);
                param.put("enable", 1);
                param.put("del", DelEnum.NORMAL.getDel());
                param.put("corpid", corpid);
                param.put("hidden", 0);
                List<PaasFormEntityExt> paasFormEntityExts= paasFormModel.getByBusinessTypes(param);
                paasFormEntityList.addAll(paasFormEntityExts);
            } else if (Objects.equals(subBusinessType,XbbRefTypeEnum.COST_ADJUST.getCode())){
                businessType = subBusinessType;
                Map<String, Object> param = new HashMap<>(16);
                param.put("businessType", businessType);
                param.put("enable", 1);
                param.put("del", DelEnum.NORMAL.getDel());
                param.put("corpid", corpid);
                param.put("hidden", 0);
                List<PaasFormEntityExt> paasFormEntityExts= paasFormModel.getByBusinessTypes(param);
                paasFormEntityList.addAll(paasFormEntityExts);
            } else if (Objects.equals(subBusinessType,XbbRefTypeEnum.RECEIPT_ORDER.getCode())){
                businessType = subBusinessType;
                Map<String, Object> param = new HashMap<>(16);
                param.put("businessType", businessType);
                param.put("enable", 1);
                param.put("del", DelEnum.NORMAL.getDel());
                param.put("corpid", corpid);
                param.put("hidden", 0);
                List<PaasFormEntityExt> paasFormEntityExts= paasFormModel.getByBusinessTypes(param);
                paasFormEntityList.addAll(paasFormEntityExts);
            } else if (Objects.equals(subBusinessType,XbbRefTypeEnum.SIGNIN.getCode())){
                //签到没有表单，用客户
                businessType = subBusinessType;
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),corpid);
                paasFormEntityExt.setBusinessType(subBusinessType);
                paasFormEntityExt.setId(0L);
                paasFormEntityList.add(paasFormEntityExt);
            } else if (Objects.equals(subBusinessType,XbbRefTypeEnum.CONTRACT_COMPARE_RESULT.getCode())) {
                PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
                paasFormEntityExt.setId(0L);
                paasFormEntityExt.setAppId(0L);
                paasFormEntityExt.setMenuId(0L);
                paasFormEntityExt.setName(XbbRefTypeEnum.CONTRACT_COMPARE_RESULT.getName());
                paasFormEntityExt.setDistributorMark(DistributorMarkEnum.OTHER.getCode());
                paasFormEntityExt.setBusinessType(subBusinessType);
                paasFormEntityList.add(paasFormEntityExt);
            } else {
                businessType = ListBusinessTypeEnum.getBusinessType(subBusinessType);
                List<Integer> businessType4Distributor = XbbRefTypeEnum.getSpecialBusinesssHasDistributor();
                if (Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                    paasFormEntityList = getEnableFormList(corpid, loginUser, businessType, null, DistributorMarkEnum.DISTRIBUTOR.getCode());
                } else if (StockConstant.STOCK_TYPE_LIST.contains(subBusinessType)) {
                    paasFormEntityList = getEnableFormList(corpid, loginUser, subBusinessType, null, null);
                } else if (Objects.equals(subBusinessType, XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode())) {
                    if (Objects.nonNull(loginUser)) {
                        if (Objects.nonNull(loginUser.getPermSet())) {
                            if (loginUser.getPermSet().contains(ProPermissionAliasEnum.CUSTOMER_PUBLIC.getAlias())) {
                                paasFormEntityList = getEnableFormList(corpid, loginUser, businessType, null, DistributorMarkEnum.OTHER.getCode());
                            }
                        }
                    } else {
                        paasFormEntityList = getEnableFormList(corpid, loginUser, businessType, null, DistributorMarkEnum.OTHER.getCode());
                    }
                } else if (Objects.equals(subBusinessType, XbbRefTypeEnum.CLUE_PUBLIC.getCode())) {
                    if (Objects.nonNull(loginUser)) {
                        if (Objects.nonNull(loginUser.getPermSet())) {
                            if (loginUser.getPermSet().contains(ProPermissionAliasEnum.CLUE_PUBLIC.getAlias())) {
                                paasFormEntityList = getEnableFormList(corpid, loginUser, businessType, null, DistributorMarkEnum.OTHER.getCode());
                            }
                        }
                    } else {
                        paasFormEntityList = getEnableFormList(corpid, loginUser, businessType, null, DistributorMarkEnum.OTHER.getCode());
                    }
                }  else if (businessType4Distributor.contains(subBusinessType)) {
                    //同时读取经销商、非经销商模板
                    paasFormEntityList = getEnableFormList(corpid, loginUser, businessType, null, null);
                } else {
                    paasFormEntityList = getEnableFormList(corpid, loginUser, businessType, null, DistributorMarkEnum.OTHER.getCode());
                }
            }
        } else {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("appId", form.getAppId());
            param.put("menuId", form.getMenuId());
            param.put("del", DelEnum.NORMAL.getDel());
            paasFormEntityList = paasFormModel.list(param);
        }
        List<EnablePojo> enablePojoList = new ArrayList<>();
//        如果是查看签到，则过滤掉权限校验
        if((!Objects.equals(subBusinessType,XbbRefTypeEnum.SIGNIN.getCode()))) {
            paasFormModel.removeByPermission(paasFormEntityList, loginUser);
        }
        if (Objects.equals(subBusinessType, XbbRefTypeEnum.STOCK_SEARCH.getCode())) {
            CompanyConfigEntity enableBatchConfig = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ENABLE_BATCH_SHELF_MANAGEMENT.getAlias(), corpid);
            for (PaasFormEntityExt paasFormEntityExt : paasFormEntityList) {
                if (Objects.equals(paasFormEntityExt.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode())) {
                    paasFormEntityExt.setName(XbbRefTypeEnum.STOCK_SEARCH.getName());
                    // 预警查询
                    PaasFormEntityExt waringSearchForm = new PaasFormEntityExt();
                    waringSearchForm.setName(XbbRefTypeEnum.WARNING_SEARCH.getName());
                    waringSearchForm.setAppId(paasFormEntityExt.getAppId());
                    waringSearchForm.setMenuId(paasFormEntityExt.getMenuId());
//                    waringSearchForm.setId(paasFormEntityExt.getId());
                    waringSearchForm.setId(Long.valueOf(ListGroupEnum.WARNING_SEARCH.getCode()));
                    waringSearchForm.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
                    paasFormEntityList.add(waringSearchForm);
                    if (Objects.nonNull(enableBatchConfig) && Objects.equals(enableBatchConfig.getConfigValue(), BasicConstant.IS_USE.toString())) {
                        // 批次保质期查询
                        PaasFormEntityExt guaranteeSearchForm = new PaasFormEntityExt();
                        guaranteeSearchForm.setName(XbbRefTypeEnum.GUARANTEE_SEARCH.getName());
                        guaranteeSearchForm.setAppId(paasFormEntityExt.getAppId());
                        guaranteeSearchForm.setMenuId(paasFormEntityExt.getMenuId());
//                    guaranteeSearchForm.setId(paasFormEntityExt.getId());
                        guaranteeSearchForm.setId(Long.valueOf(ListGroupEnum.GUARANTEE_SEARCH.getCode()));
                        guaranteeSearchForm.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
                        paasFormEntityList.add(guaranteeSearchForm);
                    }
                    break;
                }
            }
        }
        return paasFormEntityList;
    }

    @Override
    public List<EnablePojo> getSaasTemplateList(String corpid, PaasFormEntityExt form,  Integer subBusinessType, UserVO loginUser) throws XbbException {
        List<PaasFormEntityExt> paasFormEntityList = getSaasFormList(corpid, form, subBusinessType, loginUser);
        Integer businessType = changeBusinessType(subBusinessType);
        List<EnablePojo> enablePojoList = new ArrayList<>();

        for (PaasFormEntityExt entityExt : paasFormEntityList){
            EnablePojo enablePojo = new EnablePojo();
            enablePojo.setAppId(entityExt.getAppId());
            enablePojo.setMenuId(entityExt.getMenuId());
            enablePojo.setFormId(entityExt.getId());
            enablePojo.setFormName(entityExt.getName());
            enablePojo.setBusinessType(entityExt.getBusinessType());
            enablePojo.setDistributorMark(entityExt.getDistributorMark());
            if (StockConstant.STOCK_TYPE_LIST.contains(subBusinessType)) {
                enablePojo.setBusinessType(businessType);
            }
            enablePojoList.add(enablePojo);
        }
        if (Objects.equals(SaasMarkEnum.SAAS.getCode(), form.getSaasMark()) && Objects.equals(businessType,XbbRefTypeEnum.WORK_REPORT.getCode())){
            // 业务类型为工作报告时加个空对象
            enablePojoList.add(new EnablePojo());
        }
        return enablePojoList;
    }

    public static Integer changeBusinessType(Integer subBusinessType) {
        List<Integer> list= Arrays.asList(XbbRefTypeEnum.CUSTOMER_STATEMENT_STATISTIC.getCode(), XbbRefTypeEnum.COST_ADJUST.getCode(), XbbRefTypeEnum.SIGNIN.getCode());
        Integer businessType;
        if (list.contains(subBusinessType)){
            businessType = subBusinessType;
        } else {
            businessType = ListBusinessTypeEnum.getBusinessType(subBusinessType);
        }
        return businessType;
    }


    @Override
    public void setTemplate(String corpid, PaasFormEntityExt form, Integer subBusinessType, UserVO loginUser, List<FieldAttrEntity> explainList, Integer editable) throws XbbException {
        List<EnablePojo> list = getSaasTemplateList(corpid, form, subBusinessType, loginUser);
        FieldAttrEntity templateFieldAttrEntity = new FieldAttrEntity();
        if (list.size() == 1) {
            templateFieldAttrEntity.setVisible(0);
        } else {
            templateFieldAttrEntity.setVisible(1);
        }
        templateFieldAttrEntity.setAttrName(getAttrName(form.getBusinessType()));
        templateFieldAttrEntity.setAttr(FieldTypeEnum.TEMPLATE.getAlias());
        templateFieldAttrEntity.setAttrType(FieldTypeEnum.TEMPLATE.getEsalias());
        templateFieldAttrEntity.setFieldType(FieldTypeEnum.TEMPLATE.getType());
        templateFieldAttrEntity.setEditable(editable);
        templateFieldAttrEntity.setComboType(0);
        templateFieldAttrEntity.setDefaultAttr(new DefaultAttrPoJo());
        //新建一个集合用于存放ItemPoJo实体
        Long formId = form.getId();
        List<ItemPoJo> templateItem = new ArrayList<>();
        for (EnablePojo enablePojo : list) {
            //创建ItemPoJo对象，并在value和text属性中设置数据
            ItemPoJo itemPoJo = new ItemPoJo();
            itemPoJo.setValue(enablePojo.getFormId());
            itemPoJo.setText(enablePojo.getFormName());
            if (Objects.equals(enablePojo.getFormId(), formId)) {
                itemPoJo.setChecked(true);
            }
            //将最后满足的itemPoJo添加到templateItem集合中
            templateItem.add(itemPoJo);
        }
        templateFieldAttrEntity.setItems(templateItem);
        explainList.add(0, templateFieldAttrEntity);
    }

    /**
     * 获取多模板的模板名称
     * @param businessType
     * @return
     */
    private static String getAttrName(Integer businessType) {
        Map<Integer, String> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), I18nMessageUtil.getMessage(I18nStringConstant.CUSTOMER_TEMPLATE));
        map.put(XbbRefTypeEnum.CONTRACT.getCode(), I18nMessageUtil.getMessage(I18nStringConstant.CONTRACT_TEMPLATE));
        map.put(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), I18nMessageUtil.getMessage(I18nStringConstant.OPPORTUNITY_TEMPLATE));
        map.put(XbbRefTypeEnum.CLUE.getCode(), I18nMessageUtil.getMessage(I18nStringConstant.CLUE_TEMPLATE));

        return map.get(businessType);
    }
}
